﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections;
using Tracker.Mobile.Droid.TrackerWebService;
using System.Collections.Generic;
using System.Threading;
using Tracker.Mobile.Droid.Adapters;
using Tracker.Mobile.Droid.Services;
using Tracker.Mobile.Droid.Receivers;

namespace Tracker.Mobile.Droid.Activities
{
    [Activity(Label = "Tracker", Icon = "@drawable/icon")]
    public class Home : BaseTabActivity
    {
        private ListView _positionsList;
        private Spinner _intervals;
        private EditText _username;
        private EditText _email;
        private EditText _oldPassword;
        private EditText _newPassword;
        private EditText _confirmPassword;
        private Button _save;

        private IList<PositionDTO> _positions;
        private IList<string> _intervalTimes;

        private PositionAdapter _positionAdapter;
        private ISharedPreferences _preferences;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Home);
            Initialize();
        }

        protected override void OnDestroy()
        {
            _preferences.Edit().PutBoolean(PreferenceKeys.ServiceRunning, false).Commit();
            base.OnDestroy();
        }

        private void Initialize()
        {
            _positionsList = FindViewById<ListView>(Resource.Id.Positions);
            _intervals = FindViewById<Spinner>(Resource.Id.PositionInterval);
            _username = FindViewById<EditText>(Resource.Id.Username);
            _email = FindViewById<EditText>(Resource.Id.Email);
            _oldPassword = FindViewById<EditText>(Resource.Id.OldPassword);
            _newPassword = FindViewById<EditText>(Resource.Id.NewPassword);
            _confirmPassword = FindViewById<EditText>(Resource.Id.ConfirmNewPassword);
            _save = FindViewById<Button>(Resource.Id.SaveAccount);

            _username.Text = Username;
            _email.Text = Email;

            _save.Click += (sender, args) =>
            {

            };

            InitializePositions();
            _intervalTimes = Resources.GetStringArray(Resource.Array.IntervalValues);
            _preferences = GetSharedPreferences(Global.Preferences, FileCreationMode.Private);

            if (!_preferences.GetBoolean(PreferenceKeys.ServiceRunning, false))
            {
                Intent locationService = new Intent(this, typeof(LocationService));
                StartService(locationService);
                _preferences.Edit().PutBoolean(PreferenceKeys.ServiceRunning, true).Commit();
            }

            LocationUpdate locationUpdate = new LocationUpdate(() => InitializePositions());
            RegisterReceiver(locationUpdate, new IntentFilter("LocationUpdate"));

            InitializeTabs();

            _intervals.ItemSelected += (sender, args) =>
            {
                var interval = Int32.Parse(_intervalTimes[args.Position]);
                var locationService = new Intent(this, typeof(LocationService));
                bool stopped = StopService(locationService);

                Minutes = interval;
                var newLocationService = new Intent(this, typeof(LocationService));
                StartService(newLocationService);
                _preferences.Edit().PutBoolean(PreferenceKeys.ServiceRunning, true).Commit();
            };
        }

        private void InitializeTabs()
        {
            AddTab("Home", "Home", Resource.Id.Home);
            AddTab("Settings", "Settings", Resource.Id.Settings);
            AddTab("Account", "Account", Resource.Id.Account);
        }

        private void AddTab(string tag, string title, int viewID)
        {
            TabHost.TabSpec tab = TabHost.NewTabSpec(tag);

            tab.SetIndicator(title);
            tab.SetContent(viewID);
            TabHost.AddTab(tab);
        }

        private void InitializePositions()
        {
            ProgressDialog dialog = Util.CreateProgressDialog(this, ProgressDialogStyle.Spinner, "Please Wait", "Loading Positions");

            ThreadPool.QueueUserWorkItem(state =>
            {
                _positions = WebService.GetPositions(UserID);
                _positionAdapter = new PositionAdapter(this, _positions);

                RunOnUiThread(() =>
                {
                    _positionsList.SetAdapter(_positionAdapter);
                    dialog.Dismiss();
                });
            });
        }
    }
}

